package com.atguigu.spzx.order.service.impl;

import com.atguigu.cart.feign.CartFeignClient;
import com.atguigu.product.feign.ProductFeignClient;
import com.atguigu.spzx.model.dto.order.OrderInfoDto;
import com.atguigu.spzx.model.pojo.h5.CartInfo;
import com.atguigu.spzx.model.pojo.h5.UserInfo;
import com.atguigu.spzx.model.pojo.h5.UserInfoAuthContextUtil;
import com.atguigu.spzx.model.pojo.order.OrderInfo;
import com.atguigu.spzx.model.pojo.order.OrderItem;
import com.atguigu.spzx.model.pojo.order.OrderLog;
import com.atguigu.spzx.model.pojo.product.ProductSku;
import com.atguigu.spzx.model.pojo.user.UserAddress;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.h5.TradeVo;
import com.atguigu.spzx.order.mapper.OrderItemMapper;
import com.atguigu.spzx.order.mapper.OrderLogMapper;
import com.atguigu.spzx.order.mapper.OrderMapper;
import com.atguigu.spzx.order.service.OrderService;
import com.atguigu.spzx.user.client.UserFeignClient;
import com.atguigu.spzx.utils.DYLAssert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {
    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    /**
     * @return TradeVo
     * @doc: 确认订单
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public TradeVo trade() {
        TradeVo tradeVo = new TradeVo();
        // 1、通过feign获取购物车中的勾选项
        Result<List<CartInfo>> allChecked = cartFeignClient.getAllChecked();
        List<CartInfo> cartInfos = allChecked.getData();
        List<OrderItem> orderItemList = new ArrayList<>();
        tradeVo.setTotalAmount(BigDecimal.valueOf(0));
        // 2、生成OrderItem，存入tradeVo
        for (CartInfo cartInfo : cartInfos) {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItemList.add(orderItem);
            tradeVo.setTotalAmount(tradeVo.getTotalAmount()
                    .add(orderItem.getSkuPrice().multiply(BigDecimal.valueOf(orderItem.getSkuNum()))));
        }
        // 3、TradeVo 总金额和订单列表
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }


    /**
     * @param orderInfoDto
     * @doc: 提交订单
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        // 获取当前用户对象
        UserInfo userInfo = UserInfoAuthContextUtil.get();

        // 订单列表
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTotalAmount(BigDecimal.valueOf(0));
        orderInfo.setOriginalTotalAmount(BigDecimal.valueOf(0));
        for (OrderItem item : orderItemList) {
            // 检查库存
            Result<ProductSku> skuResult = productFeignClient.getBySkuId(item.getSkuId());
            ProductSku productSku = skuResult.getData();
            DYLAssert.isTrue(productSku.getStockNum() >= item.getSkuNum(), "库存不足");

            orderInfo.setTotalAmount(orderInfo.getTotalAmount().add(
                    productSku.getSalePrice().multiply(BigDecimal.valueOf(item.getSkuNum()))
            ));
            orderInfo.setOriginalTotalAmount(orderInfo.getOriginalTotalAmount().add(
                    productSku.getCostPrice().multiply(BigDecimal.valueOf(item.getSkuNum()))
            ));
        }
        // 订单信息
        orderInfo.setUserId(userInfo.getId());
        orderInfo.setNickName(userInfo.getNickName());
        // 时间戳+UUId生成随机订单号
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()) + UUID.randomUUID().toString().replace("-",""));
        orderInfo.setOrderStatus(0);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setOrderItemList(orderItemList);

        // 订单地址信息
        UserAddress userAddress = userFeignClient.findUserAddress(orderInfoDto.getUserAddressId()).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        if (StringUtils.isNotEmpty(userAddress.getProvinceCode())) {
            orderInfo.setReceiverProvince(userFeignClient.getRegionByCode(userAddress.getProvinceCode()).getData().getId());
        }
        if (StringUtils.isNotEmpty(userAddress.getCityCode())) {
            orderInfo.setReceiverCity(userFeignClient.getRegionByCode(userAddress.getCityCode()).getData().getId());
        }
        if (StringUtils.isNotEmpty(userAddress.getDistrictCode())) {
            orderInfo.setReceiverDistrict(userFeignClient.getRegionByCode(userAddress.getDistrictCode()).getData().getId());
        }
        orderInfo.setCouponAmount(BigDecimal.valueOf(0));

        // 订单项 设置对应订单id
        orderMapper.insert(orderInfo);
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
        }
        orderItemMapper.insert(orderItemList);
        // 保存订单信息、订单项信息、订单日志信息
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    @Override
    public TradeVo buyProduct(Long skuId) {
        TradeVo tradeVo = new TradeVo();
        ProductSku productSku = productFeignClient.getBySkuId(skuId).getData();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuNum(1);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        tradeVo.setTotalAmount(productSku.getSalePrice());
        tradeVo.setOrderItemList(new ArrayList<>());
        tradeVo.getOrderItemList().add(orderItem);
        return tradeVo;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        return orderMapper.selectById(orderId);
    }

    @Override
    public PageInfo<OrderInfo> getOrderPage(Integer pageNum, Integer pageSize, Integer orderStatus) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderInfo> orders = orderMapper.getOrderPage(orderStatus);
        return new PageInfo<>(orders);
    }

    @Override
    public OrderInfo findByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderMapper.selectOne(new QueryWrapper<OrderInfo>().eq("order_no", orderNo));
        // 获取orderList
        List<OrderItem> orderItems = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_id", orderInfo.getId()));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }
}
